<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item><a href="/permission/admin">区域管理</a></el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <div style="margin: 0 0 20px 0;">
      <el-button type="primary" size="medium"
                 @click="$router.push('/house/section/add-new')">
        添加区域
      </el-button>
    </div>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>
      <el-table-column prop="name" label="名称"  align="center"
                       show-overflow-tooltip></el-table-column>
      <el-table-column prop="isDisplay" label="是否显示" width="180" align="center"
                       show-overflow-tooltip>
        <template slot-scope="scope">
          <el-switch
              @change="toggleEnable(scope.row)"
              v-model="scope.row.isDisplay"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#999">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="子集类别" width="100" align="center">
        <template slot-scope="scope">
        <el-button size="small" :disabled="scope.row.isParent == 0"
                   @click="showSubSectionList(scope.row)">查看
                   </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" circle
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" circle
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="text-align: right; margin: 10px auto;">
      <el-pagination
          @current-change="changePage"
          layout="total, prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize">
      </el-pagination>
    </div>

    <div v-if="currentParentId != 0" style="margin-top: 10px; text-align: right;">
      <el-button size="small" @click="goBack()">返回</el-button>
    </div>

    <el-dialog title="编辑管理员" :visible.sync="dialogFormVisible">
      <el-form :model="editForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="父级ID" prop="parentId">
          <el-input v-model="editForm.parentId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="层级" prop="depth">
          <el-input v-model="editForm.depth" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否为父级" prop="isParent">
          <el-switch
              v-model="editForm.isParent"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ccc">
          </el-switch>
        </el-form-item>
        <el-form-item label="是否显示" prop="isDisplay">
          <el-switch
              v-model="editForm.isDisplay"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ccc">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleListOptions: [],
      tableData: [],
      total: 0,
      pageSize: 0,
      currentPage: 1,
      dialogFormVisible: false,
      editForm: {
        id:'',
        name: '',
        parentId:'',
        depth:'',
        isParent:'',
        isDisplay:'',
      },
      rules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}
        ],
        parentId: [
          {required: true, message: '请输入父级类别ID', trigger: 'blur'},
          {pattern: /^\d+$/, message: '请选择有效的父级类别', trigger: 'blur'}
        ],
        depth: [
          {required: true, message: '请输入层级', trigger: 'blur'},
          {pattern: /^[1-9]\d*$/, message: '请选择有效的层级', trigger: 'blur'}
        ],
        isParent: [
          {required: true, message: '请选择是否为父级', trigger: 'blur'},
        ],
        isDisplay: [
          {required: true, message: '请选择是否显示', trigger: 'blur'},
        ]
      },
      currentParentId: 0,
      history: []
    }
  },
  methods: {
    goBack() {
      console.log('goBack, start...');
      for(let i = 0; i < this.history.length; i++) {
        console.log(this.history[i].id + ' ' + this.history[i].name);
      }
      console.log('---------------')

      let parentCategory = this.history[this.history.length - 1];
      this.currentParentId = parentCategory.parentId;
      this.loadSectionList();
      this.history.pop();

      console.log('goBack, done.');
      for(let i = 0; i < this.history.length; i++) {
        console.log(this.history[i].id + ' ' + this.history[i].name);
      }
      console.log('---------------')
    },
    showSubSectionList(section) {
      this.history[section.depth - 1] = section;

      console.log('showSubSectionList');
      for(let i = 0; i < this.history.length; i++) {
        console.log(this.history[i].id + ' ' + this.history[i].name);
      }
      console.log('---------------')

      this.currentParentId = section.id;
      this.loadSectionList();
    },
    openEditDialog(section) {
      let url = 'http://localhost:9200/section/standard?id=' + section.id;
      this.axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadSectionList();
            }
          });
        }
      });
    },
    toggleEnable(section) {
      let displayText = ['隐藏', '显示'];
      let url = 'http://localhost:9200/section/' + section.id;
      let display = section.isDisplay;
      if (display == 1) {
        url += '/display';
      } else {
        url += '/hidden';
      }
      console.log('url = ' + url);

      this.axios.post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '将【' + section.name + '】的显示状态修改为【' + displayText[display] + '】成功！',
            type: 'success'
          });
          this.loadSectionList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadSectionList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadSectionList();
            }
          });
        }
      }).catch(err => {
        let message = '服务器响应错误！';
        this.$alert(message, '操作失败', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      });
    },
    submitEditForm(){
      let url = 'http://localhost:9200/section/update';
      console.log('url = ' + url);


      let formData = this.qs.stringify(this.editForm);

      console.log("formData=" + formData)
      let localJwt = localStorage.getItem('localJwt');


      this.axios
          .create({
            'headers': {
              'Authorization':localJwt
            }
          })
       .post(url,formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state==20000){
          this.$message({
            message: '修改区域成功',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.loadSectionList();
        } else if (jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadSectionList();
            }
          });
        }else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }

      })
    },
    openDeleteConfirm(section) {
      this.$confirm('此操作将永久删除【' + section.id + '-' + section.name + '】管理员，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(section);
      }).catch(() => {
      });
    },
    handleDelete(section) {
      let url = 'http://localhost:9200/section/delete';

      let formData = 'id=' + section.id;

      let localJwt = localStorage.getItem('localJwt');


      this.axios
          .create({
            'headers': {
              'Authorization':localJwt
            }
          })
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除区域成功！',
            type: 'success'
          });
          this.loadSectionList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadSectionList();
            }
          });
        } else if (jsonResult.state == 40900) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    changePage(value) {
      this.$router.replace('?page=' + value);
      this.loadSectionList();

    },
    loadSectionList() {
      let url = 'http://localhost:9200/section/list-by-parent?parentId=' + this.currentParentId;

      this.axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    }
  },
  mounted() {
    this.loadSectionList();
  }
}
</script>
